import React, { Component } from 'react'
import Info from "components/info"
import SubjectService from "./subject.service";
import { messages } from "share/common";
import AdvancedTable from "components/advanced-table";
import { Badge, Button, Input } from "antd";
import SlideFrame from "components/slide-frame";
import SubjectRule from "containers/finance-setting/subject-sheet/subject-rule";
import Importer from "components/template/importer/index";
import AsyncExport from "components/template/async-export/async-export";
import { connect } from "react-redux";
import SubjectDetailRule from './subject-detail-rule'
import debounce from "lodash.debounce"
import Template from "components/UI/template"

const { Middle, Header } = Template;

@connect(mapStateToProps)
class SubjectDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      infoLoading: false,
      info: {},
      searchValue: ''
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  attributes = [
    { title: messages('finance-5.key54')/*科目表编码*/, dataIndex: 'accountSetCode' },
    { title: messages('finance-5.key55')/*科目表名称*/, dataIndex: 'accountSetDesc' },
    { title: messages('common.column.status')/*状态*/, dataIndex: 'enabled', render: value => value ? messages('finance-5.key48')/*启用temp*/ : messages('finance-5.key56')/*禁用temp*/ }
  ];

  columns = [
    { title: messages('finance-5.key45')/*科目代码*/, dataIndex: 'accountCode' },
    { title: messages('finance-5.key46')/*科目名称*/, dataIndex: 'accountDesc' },
    { title: messages('finance-5.key50')/*余额方向*/, dataIndex: 'balanceDirectionName' },
    { title: messages('finance-5.key47')/*科目类型*/, dataIndex: 'accountTypeName' },
    { title: messages('finance-5.key51')/*报表类型*/, dataIndex: 'reportTypeName' },
    { title: messages('finance-5.key49')/*是否汇总*/, dataIndex: 'summaryFlag',
      render: value => value ? messages('common.yes')/*是*/ : messages('common.no')/*否*/
    },
    { title: messages('common.column.status')/*状态*/, dataIndex: 'enabled',
      render: enabled => <Badge status={enabled ? 'success' : 'error'}
                                text={enabled ? messages('finance-5.key48')/*启用temp*/ : messages('finance-5.key56')/*禁用temp*/}/>
    }
  ];

  searchForm = [
    {
      id: 'accountType', label: messages('finance-5.key47')/*科目类型*/, component: 'Selector',
      props: {
        params: {type: 2205},
        type: 'value_list'
      },
      dataIndex: 'accountTypeName'
    }
  ];

  componentWillMount() {
    this.getInfo();
  }

  getInfo = () => {
    const { id } = this.props.params;
    this.setState({ infoLoading: true });
    SubjectService.getSubjectDetail(id)
      .then(res => {
        this.setState({ info: res.data });
      })
      .finally(() => {
        this.setState({ infoLoading: false });
      })
  };

  service = (page, size, searchParams) => {
    const { id } = this.props.params, { searchValue } = this.state;
    return SubjectService.getSubjectDetailList({ page, size, ...searchParams, accountSetId: id, info: searchValue })
  };

  handleEditInfo = () => {
    const { info } = this.state;
    SlideFrame.open({
      content: SubjectRule,
      title: messages('finance-5.key57')/*科目表定义*/,
      params: { record: info },
      afterClose: () => this.getInfo()
    }, this);
  };

  handleCreate = record => {
    const { id } = this.props.params;
    SlideFrame.open({
      content: SubjectDetailRule,
      title: messages('finance-5.key57')/*科目表定义*/,
      params: { record, id },
      afterClose: flag => flag && this.tabRef.getList()
    }, this);
  };

  handleSearch = searchValue => {
    this.setState({ searchValue }, () => {
      this.tabRef.getList();
    })
  };

  render() {
    const { infoLoading, info, searchValue } = this.state;
    const { language, loginUser, tenantInfo } = this.props;
    const { id } = this.props.params;
    return (
      <Template>
        <Header>
          <Info
            title={messages('finance-5.key24')/*基础信息*/}
            attributes={this.attributes}
            dataSource={info}
            loading={infoLoading}
          >
            <Button type='primary' onClick={this.handleEditInfo}>{messages('common.edit')/*编辑*/}</Button>
          </Info>
          <h3 style={{marginBottom: 0}}>{messages('finance-5.key58')/*科目明细*/}</h3>
        </Header>
        <Middle>
          <AdvancedTable.SimpleTable
            columns={this.columns}
            service={this.service}
            onRef={ref => this.tabRef = ref}
            searchForm={this.searchForm}
            rowKey='id'
            onRow={record => ({
              onClick: () => this.handleCreate(record)
            })}
          >
            <div style={{ position: 'relative', marginBottom: '10px' }}>
              <Button type="primary" onClick={() => this.handleCreate({})} style={{ marginRight: '8px' }}>{messages('common.create')/*新建*/}</Button>
              <Importer
                btnName={messages('finance-5.key59')/*导入科目*/}
                btnProps={{type: 'default'}}
                onOK={() => this.tabRef.getList()}
                errorTableData={data => Importer.getUploadResult(data)}
                templateOptions={{
                  templateList: [{
                    downloadName: messages('finance-5.key60')/*科目表*/,
                    templateName: messages('finance-5.key60')/*科目表*/,
                    downloadUrl: `/ledger/api/download/template`,
                    downloadMethod: 'post',
                    downloadParams: {
                      templateType: 'ACCOUNT',
                      language: language.code
                    }
                  }]
                }}
                uploadOptions={{
                  uploadUrl: `/ledger/api/accounts/import?accountSetId=${id}&tenantId=${tenantInfo.id}&operatorOid=${loginUser.userOID}`,
                  listenUrl: '/ledger/api/transaction/log/query/by'
                }}
                uploadResultOptions={{
                  shouldDownloadErrorInfo: true,
                  getErrorTableVisible: uploadResult => uploadResult && uploadResult.failureEntities > 0,
                  errorUrl: '/ledger/api/transaction/log/export/errorMsg',
                  errorParams: {language: language.code}
                }}
              />
              <AsyncExport
                title={messages('finance-5.key61')/*导出科目详情*/}
                style={{ display: 'inline-block', marginLeft: '8px' }}
                params={{
                  tenantId: loginUser.tenantId,
                  operatorOid: loginUser.userOID,
                  implName: 'accountsDownloadImpl',
                  language: language.code,
                  isAsync: true,
                  otherDownloadMsg: {
                    accountSetId: id,
                    accountType: this.tabRef ? this.tabRef.state.searchParams.accountType : undefined,
                    accountCodeOrName: searchValue,
                  }
                }}
              />
              <Input.Search
                style={{
                  width: '300px',
                  position: 'absolute',
                  bottom: '0',
                  right: '0'
                }}
                placeholder={messages('finance-5.key62')/*科目代码/名称*/}
                onChange={(e) => this.handleSearch(e.target.value)}
              />
            </div>
          </AdvancedTable.SimpleTable>
        </Middle>
      </Template>
    )
  }

}

function mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant,
    loginUser: state.login.loginUser,
    language: state.main.language
  }
}

export default SubjectDetail
